#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

import os, pickle
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings
from djangoproject.models import *


class DynForm(forms.Form):    
    """Dynamic form that allows the user to change and then verify the data that was parsed"""
    def setFields(self, kwds):
        """Set the fields in the form"""
        keys = kwds.keys()
        keys.sort()
        for k in keys:
            self.fields[k] = kwds[k]            
    def setData(self, kwds):
        """Set the data to include in the form"""
        self.is_bound = True 
        keys = kwds.keys()
        keys.sort()
        for k in keys:
            self.data[k] = kwds[k]
    def validate(self, post):
        """Validate the contents of the form"""
        for name,field in self.fields.items():
            try:
                field.clean(post[name])
            except ValidationError, e:
                self.errors[name] = e.messages
    class Media:  #Should not affect any non-Map forms
        js=("http://localhost/openlayers/OpenLayers.js",)
















def WalkDirectory(Root, Directories = [], Files = {}):
    """Root=the root directory that the walk starts on, or a subdirectory under the root that was recursively called
       Directories=An Empty List to Start, the full path of each directory under Root, including Root Itself
       Files=An Empty Dictionary to Start, the name of each file, with a full path.  The value of each file is the
             file last modify date"""
    for filename in os.listdir(Root):
        if(os.path.isdir(Root + filename)):
            WalkDirectory(Root + filename + '/', Directories, Files)
            Directories.append(Root + filename + '/')
        else:
            Files[Root + filename] = os.path.getmtime(Root + filename)
    return Directories, Files

def CreateDirectories(Directories):
    for directory in Directories:
        os.system("sudo -u apachescript sudo mkdir " + directory)
            

def GetRemoteFile(FileLocation, PickleIndicator=False):
    os.system("sudo -u apachescript sudo wget -O " + djangoproject.settings.COOPIPTemporaryFileName + 
              " http://" + djangoproject.settings.COOPIPServerIPAddress + '/' + FileLocation)
    File=open(djangoproject.settings.COOPIPTemporaryFileName, 'rb')
    if(PickleIndicator):
        Results=pickle.load(File)
    else:
        ResultsList=[]
        for char in File.read():
            ResultsList.append(char)
        Results=''.join(ResultsList)
    File.close()
    os.system("sudo -u apachescript sudo rm " + djangoproject.settings.COOPIPTemporaryFileName)
    return Results




def GetLongMapNumber(assembly):
    if(len(assembly.oldmapnumber) < 2):
        return 'UNKNOWN'
    Numbers=assembly.oldmapnumber.split('-')
    if(not Numbers[0]):
        return 'UNKNOWN, Initial "-"'
    if(Numbers[0][0] == 'E'):
        #Handle E Number here
        FirstNumber='500'
        SecondNumber=Numbers[0][1:].rjust(3, '0')
        if(len(Numbers) == 2):
            ThirdNumber=Numbers[1].rjust(5, '0')
        else:
            ThirdNumber=Numbers[1].rjust(2, '0') + Numbers[2].rjust(3, '0')                
        return FirstNumber + SecondNumber + ThirdNumber
    if(len(Numbers) == 4):
        FirstNumber=Numbers[0] + '00'
        SecondNumber=Numbers[1]
        ThirdNumber=Numbers[2].rjust(3, '0')
        FourthNumber=''
        FifthNumber=Numbers[3].rjust(3, '0')
        return FirstNumber + SecondNumber + ThirdNumber + FourthNumber + FifthNumber
    if(len(Numbers) == 5):
        FirstNumber=Numbers[0] + '00'
        SecondNumber=Numbers[1]
        ThirdNumber=Numbers[2]
        FourthNumber=Numbers[3].rjust(2, '0')
        FifthNumber=Numbers[4].rjust(3, '0')
        return FirstNumber + SecondNumber + ThirdNumber + FourthNumber + FifthNumber
    else:
        return 'Possibly Invalid GIS Map Number:  ' + assembly.oldmapnumber


def CalculateQuality(QualityCode):
    if(QualityCode == 1):
        return str(QualityCode) + ':  Command Pending' 
    elif(QualityCode == 3):
        return str(QualityCode) + ':  Valid Data'
    elif(QualityCode == 6):
        return str(QualityCode) + ':  Success'
    elif(QualityCode == 9):
        return str(QualityCode) + ':  Invalid Data'
    elif(QualityCode == 10):
        return str(QualityCode) + ':  Substation Status'
    elif(QualityCode == 44):
        return str(QualityCode) + ':  Invalid Data EC Fail'
    elif(QualityCode == 113):
        return str(QualityCode) + ':  Pre SCE Timeout'
    return str(QualityCode)


def MakeSureNotTooManyPendingMeterPings(Substation):
    """Do not set any meters to be pinged if there are more meters pending to go out to AMR than the limit of the MeterPingMaximumPendingCommands
       These pings would just queue up and make the program very unresponsive to changes to the ping rate"""
    Now = datetime.datetime.now()
    PendingPingsCount = djangoproject.models.ipbase.Meter.objects.filter(Substation=Substation).filter(SendPingToAMRIndicator=True).count()
    if( (PendingPingsCount > djangoproject.settings.MeterPingMaximumPendingCommands) or ((Now - Substation.LastUpdateDateTime).total_seconds() > 90) ):
        return False
    return True

def StringTimeSinceEvent(CurrentDateTime, PreviousDateTime):
    if(not CurrentDateTime) or (not PreviousDateTime):
        return 'UNDEFINED'
    TimeSinceEvent = CurrentDateTime - PreviousDateTime
    String = ''
    TotalSeconds = TimeSinceEvent.total_seconds()

    if(int(TotalSeconds) / 86400):  #Seconds in a day
        String = String + str(int(TotalSeconds) / 86400) + 'd '
    TotalSeconds = TotalSeconds % 86400
    if(int(TotalSeconds) / 3600):
        String = String + str(int(TotalSeconds) / 3600) + 'h '
    TotalSeconds = TotalSeconds % 3600
    String = String + str(int(TotalSeconds) / 60) + 'm '
    return String    


def ConvertCISDisconnectDate(CISDate):
    Year = int(CISDate[:2].lstrip('0'))
    Month = int(CISDate[2:4].lstrip('0'))
    Day = int(CISDate[4:].lstrip('0'))
    if(Year > 80):
        Year = Year + 1900
    else:
        Year = Year + 2000
    date=datetime.date(Year, Month, Day)
    return date

